package net.quanter.shield.utils.bean;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import cn.hutool.core.bean.BeanUtil;

/***
 * 对象操作类
 * created by 2020-10-11
 * @author 王老实
 *
 */
public class BeanUtils extends BeanUtil {

    public static Object[] clones(Object[] objects) {
        if (objects == null) {
            return null;
        }
        if (objects.length == 0) {
            return new Object[] {};
        }
        Object[] results = new Object[objects.length];
        for (int i = 0; i < objects.length; i++) {
            results[i] = clone(objects[i]);
        }
        return results;
    }

    public static <T> T clone(final T source) {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        ByteArrayInputStream bin = null;
        ObjectInputStream ois = null;
        try {
            oos = new ObjectOutputStream(bout);
            oos.writeObject(source);
            bin = new ByteArrayInputStream(bout.toByteArray());
            ois = new ObjectInputStream(bin);
            return (T)ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                bout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bin != null) {
                try {
                    bin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
